/**
 * hnjz.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.hnjz.sys.function;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hnjz.common.AppException;
import com.hnjz.common.PKUtil;
import com.hnjz.common.YnEnum;
import com.hnjz.common.security.CtxUtil;
import com.hnjz.sys.role.RoleForm;
import com.hnjz.sys.roleFun.RoleFuncMapper;
import com.hnjz.sys.roleFun.RoleFuncOperMapper;
import com.hnjz.sys.user.User;

/**
 * 功能管理
 * 
 * @author lijingfen
 * @version $Id: FunManager.java $
 */
@Service("funManager")
public class FunManager {
    /**日志*/
    private static final Log   log = LogFactory.getLog(FunManager.class);

    @Autowired
    private FunMapper          funMapper;
    @Autowired
    private FuncOperMapper     funcOperMapper;
    @Autowired
    private RoleFuncMapper     roleFuncMapper;
    @Autowired
    private RoleFuncOperMapper roleFuncOperMapper;

    /**
     * 根据Id获取
     * 
     * @param id 功能ID
     * @return 功能
     */
    public Function getFun(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        Function fun = funMapper.findById(id);
        return fun;
    }

    /**
     * 查询功能菜单
     * 
     * @return 功能菜单列表
     * @throws Exception 
     */
    public JSONArray queryFun(String name) throws Exception {
        JSONArray re = new JSONArray();
        Function fu = new Function();
        fu.setFuncName(name);
        List<Function> pos = funMapper.findByName(fu);
        JSONObject jsonObj = null;
        for (Function ele : pos) {
            jsonObj = new JSONObject();
            jsonObj.put("id", ele.getId());
            if (StringUtils.isBlank(name) && StringUtils.isNotBlank(ele.getParent())) {
                jsonObj.put("pid", ele.getParent());
            }
            jsonObj.put("name", ele.getFuncName());
            JSONObject dataObject = new JSONObject();
            dataObject.put("title", ele.getFuncName());
            dataObject.put("note", ele.getFuncDesc());
            dataObject.put("link", ele.getLinkaddr());
            dataObject.put("order", ele.getOrderby());
            jsonObj.put("dataObject", dataObject);
            if (log.isDebugEnabled()) {
                log.debug(ele.getFuncName() + ":" + ele.getOrderby());
            }
            re.put(jsonObj);
        }
        return re;
    }

    /**
     * 保存功能
     * 
     * @param frm {@link RoleForm}
     * @throws JSONException 
     */
    public void saveFun(FunForm frm) throws AppException, JSONException {

        Function po = null;
        User user = CtxUtil.getCurUser();
        Date cur = new Date();
        if (StringUtils.isNotBlank(frm.getId())) {
            po = this.funMapper.findById(frm.getId());
        } else {
            po = new Function();
            po.setId(PKUtil.uuid());
            po.setCreator(user.getId());
            po.setCreateTime(cur);

        }
        if (StringUtils.isNotBlank(frm.getParent())) {
            po.setParent(frm.getParent());
        } else {
            po.setParent("");
        }
        po.setFuncName(frm.getFuncName());
        po.setFuncDesc(frm.getFuncDesc());
        po.setLinkaddr(frm.getLinkaddr());
        if (StringUtils.isNotBlank(frm.getOrderby())) {
            po.setOrderby(Integer.parseInt(frm.getOrderby()));
        }
        po.setIsOpen(YnEnum.Y.getCode());
        po.setIsActive(YnEnum.Y.getCode());
        po.setIsLast(YnEnum.Y.getCode());

        if (StringUtils.isNotBlank(frm.getId())) {
            this.funMapper.update(po);
        } else {
            this.funMapper.save(po);
        }
        List<FuncOper> pos = funcOperMapper.findByfunId(po.getId());
        //保存该功能的操作
        if (StringUtils.isNotBlank(frm.getData())) {
            List<String> webids = new ArrayList<String>();
            JSONObject obj = new JSONObject(frm.getData());
            JSONArray arr = obj.getJSONArray("rows");
            for (int i = 0; i < arr.length(); i++) {
                obj = arr.getJSONObject(i);
                String opid = obj.getString("id");
                FuncOper fu = null;
                if (StringUtils.isNotBlank(opid)) {
                    fu = (FuncOper) this.funcOperMapper.findById(opid);
                } else {
                    fu = new FuncOper();
                    fu.setId(PKUtil.uuid());
                    fu.setCreator(user.getId());
                    fu.setCreateTime(cur);
                    fu.setIsActive(YnEnum.Y.getCode());
                }

                fu.setFunction(po.getId());
                fu.setName(obj.getString("name"));
                fu.setLinkAddr(obj.getString("linkAddr"));
                fu.setOnclickEvent(obj.getString("onclickEvent"));
                fu.setFashion(obj.getString("fashion"));
                //保存操作
                if (StringUtils.isNotBlank(opid)) {
                    funcOperMapper.update(fu);
                } else {
                    funcOperMapper.save(fu);
                }
                webids.add(fu.getId());
            }
            //先删除不存在的操作，及操作相关的权限
            for (FuncOper ele : pos) {
                if (webids.contains(ele.getId())) {
                    continue;
                }
                roleFuncOperMapper.deleteByFuncoperId(ele.getId());
                if (log.isDebugEnabled()) {
                    log.debug("删除操作权限:" + ele.getName());
                }
                funcOperMapper.deleteById(ele.getId());
                if (log.isDebugEnabled()) {
                    log.debug("删除操作:" + ele.getName());
                }
            }

        }

    }

    /**
     * 删除功能
     * 
     * @param id ID
     */
    public void removeFun(String id) throws AppException {
        //有子节点的功能不允许删除
        List<Function> re = this.funMapper.findByPid(id);
        if (!re.isEmpty()) {
            //抛出异常,方便事物控制
            throw new AppException("当前功能有子节点，不允许删除。");
        }
        // 删除菜单相关的权限数据
        roleFuncMapper.deleteByFunId(id);
        // 删除操作相关的权限数据
        List<FuncOper> pos = funcOperMapper.findByfunId(id);
        for (FuncOper ele : pos) {
            roleFuncOperMapper.deleteByFuncoperId(ele.getId());
        }
        //删除操作相关数据
        funcOperMapper.deleteByFuncid(id);
        //删除功能
        this.funMapper.deleteById(id);

    }

    /**
     * 选择功能菜单公共页面的查询
     * 
     * @return 功能菜单列表
     * @throws Exception 
     */
    public JSONArray querySelectFunction() throws Exception {
        JSONArray re = new JSONArray();
        Function fu = new Function();
        List<Function> pos = funMapper.findByName(fu);
        JSONObject jsonObj = null;
        for (Function ele : pos) {
            jsonObj = new JSONObject();
            jsonObj.put("id", ele.getId());
            if (null != ele.getParent()) {
                jsonObj.put("pid", ele.getParent());
            }
            jsonObj.put("name", ele.getFuncName());
            re.put(jsonObj);
        }
        return re;
    }

    /**
     * 查询当前菜单有那些操作
     * 
     * @return 当前菜单有那些操作
     * @throws Exception 
     */
    public List<FuncOper> queryOptByFunction(String id) throws Exception {
        List<FuncOper> re = new ArrayList<FuncOper>();
        FuncOper obj = null;
        if (StringUtils.isBlank(id)) {
            String[] names = new String[] { "增加", "修改", "删除" };
            String[] eventNames = new String[] { "add()", "edit(this)", "del(this)", };
            String[] isTableShow = new String[] { IsShowEnum.N.getCode(), IsShowEnum.Y.getCode(),
                    IsShowEnum.Y.getCode(), };
            for (int i = 0; i < names.length; i++) {
                obj = new FuncOper();
                obj.setId("");
                obj.setOnclickEvent(eventNames[i]);
                obj.setName(names[i]);
                obj.setLinkAddr("");
                obj.setFashion(isTableShow[i]);
                re.add(obj);
            }
            return re;
        }
        List<FuncOper> pos = funcOperMapper.findByfunId(id);
        System.out.println(pos);
        for (FuncOper ele : pos) {
            obj = new FuncOper();
            obj.setId(ele.getId());
            obj.setOnclickEvent(StringUtils.defaultIfBlank(ele.getOnclickEvent(), ""));
            obj.setName(ele.getName());
            obj.setLinkAddr(StringUtils.isNotBlank(ele.getLinkAddr())? ele.getLinkAddr():"");
            obj.setFashion(ele.getFashion());
            if (log.isDebugEnabled()) {
                log.debug("菜单的操作:" + ToStringBuilder.reflectionToString(obj));
            }
            re.add(obj);
        }
        return re;
    }
}
